package com.sap.mall.search.thread;

import java.util.concurrent.*;

public class ThreadTest {

    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        CompletableFuture.runAsync(()->{
//            int i = 10 / 2;
//            System.out.println(i);
//        },executorService);

//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            return 0;
//        }, executorService);
//        Integer integer = integerCompletableFuture.get();
//        System.out.println(integer);

//          方法完成后得感知
//        CompletableFuture<Integer> exceptionally = CompletableFuture.supplyAsync(() -> {
//            int i = 10 / 0;
//            return 0;
//        }, executorService).whenComplete((res, exception) -> {
//            // 虽然能得到异常信息，但是没办法修改返回数据
//            System.out.println("res:" + res + " exception:" + exception);
//        }).exceptionally((throwable) -> {
//            // 可以感知异常，并可以修改返回数据
//            return 10;
//        });

//        CompletableFuture<Integer> exceptionally = CompletableFuture.supplyAsync(() -> {
//            int i = 10 / 4;
//            return i;
//        }, executorService).handle((res, throwable) -> {
//            if (res != null) {
//                return res * 2;
//            }
//            if (throwable != null) {
//                return 0;
//            }
//            return 0;
//        });
//        Integer integer = exceptionally.get();
//        System.out.println(integer);

        /**
         * 线程串行化，thenrun 不能获取到上一步得执行结果
         */
//        CompletableFuture<Void> exceptionally = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1启动了,当前线程:" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            return i;
//        }, executorService).thenRun(() -> System.out.println("任务2启动了,当前线程:" + Thread.currentThread().getId()));
//
//        System.out.println("main线程:"+Thread.currentThread().getId());

//        CompletableFuture<Void> exceptionally = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1启动了,当前线程:" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            return i;
//        }, executorService).thenAcceptAsync((res) -> System.out.println("任务2启动了,当前线程:" + Thread.currentThread().getId()));

//        CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1启动了,当前线程:" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            return i;
//        }, executorService).thenApplyAsync((res) -> {
//            System.out.println("任务2启动了,当前线程:" + Thread.currentThread().getId());
//            return "hello" + res;
//        });
//
//        System.out.println("result:"+result.get());
//        CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1启动了,当前线程:" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            System.out.println("任务1结束了,当前线程:" + Thread.currentThread().getId());
//            return i;
//        }, executorService);
//        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务2启动了,当前线程:" + Thread.currentThread().getId());
//            System.out.println("任务2结束了,当前线程:" + Thread.currentThread().getId());
//            return "hello";
//        }, executorService);

//        future01.runAfterBothAsync(future02,()->{
//            System.out.println("任务三开始,线程"+Thread.currentThread().getId());
//        },executorService);

//        future01.thenAcceptBothAsync(future02,(f1,f2)->{
//            System.out.println("任务3启动了,当前线程:" + Thread.currentThread().getId() +"之前得结果:"+f1+" "+f2);
//        },executorService);

//        CompletableFuture<String> fu = future01.thenCombineAsync(future02, (f1, f2) -> {
//            return f1 + " -- " + f2;
//        }, executorService);
//        System.out.println(""+fu.get());
        /**
         * 两个任务只要有一个任务完成就执行任务三
         */
//        future01.runAfterEitherAsync(future02,()->{
//            System.out.println("任务三开始："+Thread.currentThread().getId());
//        });
//        System.out.println();

        /**
         * 感知结果，不返回结果
         */
//        future01.acceptEitherAsync(future02, (res) -> {
//            System.out.println("任务三开始之前得结果：" + res);
//        });
//
//        CompletableFuture<String> future = future01.applyToEitherAsync(future02, res -> res.toString() + "哈哈", executorService);
//        System.out.println(future.get());

        /**
         * 多任务组合
         *  allOf:  等待所有任务完成
         *  anyOf:  只要有一个任务完成
         */

        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品得图片信息:" + Thread.currentThread().getId());
            return "hello.jpg";
        },executorService);
        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品得属性:" + Thread.currentThread().getId());
            return "黑色+256G";
        },executorService);
        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品得属性:" + Thread.currentThread().getId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Apple";
        },executorService);

//        CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
//         allOf.get();
//        System.out.println(futureImg.get()+futureAttr.get()+futureDesc.get());
//        System.out.println("--------------end-----------------");


        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);
        System.out.println(anyOf.get());
    }


    public static void thread(String[] args) throws ExecutionException, InterruptedException {
        // 1、启动线程方式一
        Thread01 thread01 = new Thread01();
        thread01.start();

        // 2、启动线程方式二
        new Thread(new Runable02()).start();

        // 3、启动线程方式三
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable03());
        new Thread(futureTask).start();
        // 阻塞等待整个线程执行完成，获取返回结果
        Integer result = futureTask.get();

        //=================以上三种启动线程方式都不用，将所有多线程异步任务都交给线程池执行===================
        /**
         * 区别
         *  1、 1、2不能得到返回值，3可以获取返回值
         *  2、 1、2、3都不能控制资源
         *  3、 可以控制资源，性能稳定
         *
         *  4、 线程池创建
         *      1、创建
         *          1）、Executors
         *          2）、new ThreadPoolExecutor()
         */

        // 4、线程池
        /**
         *  七大参数：
         *  int corePoolSize,
         *  int maximumPoolSize,
         *  long keepAliveTime,
         *  TimeUnit unit,
         *  BlockingQueue<Runnable> workQueue,
         *  ThreadFactory threadFactory,
         *  RejectedExecutionHandler handler
         *
         *  工作顺序
         *  1、 线程池创建，准备好core数量得核心线程，准备接受任务
         *  2、 阻塞队列满了，就直接开新线程执行，最大只能开到max指定得数量
         *  3、 max满了，就用RejectedExecutionHandler
         *  4、max都执行完成，有很多空闲，在指定得时间keepAliveTime 以后，释放（max-core）这些线程
         *
         *
         *  假如一个线程池core 7 max 20 queue 50, 100 个并发进来怎么分配
         *  7个会立即得到执行，50个会进入队列，再开13个进行执行，剩下得30得拒绝策略
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        Executors.newCachedThreadPool();  // core是0，所有都可回收
        Executors.newFixedThreadPool(10); // 固定大小，core=max,都不可回收
        Executors.newScheduledThreadPool(10); //定时任务得线程池
        Executors.newSingleThreadExecutor(); // 单线程得线程池，后台队队列中获取任务挨个执行


    }


    public static class Thread01 extends Thread {
        @Override
        public void run() {
            int i = 10 / 2;
            System.out.println(i);
        }
    }


    public static class Runable02 implements Runnable {

        @Override
        public void run() {
            int i = 10 / 2;
            System.out.println(i);
        }
    }


    public static class Callable03 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            int i = 10 / 2;
            System.out.println(i);
            return i;
        }
    }

}
